<template>
  <a-modal
    :title="title"
    :width="720"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="供应商简称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['name', {rules: [{required: true, min: 2, message: '请输入至少2个字符'}]}]"
          />
        </a-form-item>
        <a-form-item label="供应商全称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['full_name', {rules: [{required: false, min: 2, message: '请输入至少2个字符'}]}]"
          />
        </a-form-item>
        <a-form-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['phone', {rules: [{ required: true, message: '请输入手机号码', whitespace: true,}, { validator: phoneCheck.bind(this) }]}]"
          />
        </a-form-item>

        <a-form-item label="仓库接入类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group
            v-decorator="['storage_type', { initialValue: 10, rules: [{ required: true }] }]"
            @change="onForceUpdate()"
          >
            <a-radio :value="STEnum.API.value">{{ STEnum.API.name }}</a-radio>
            <a-radio :value="STEnum.LOCAL.value">{{ STEnum.LOCAL.name }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <div v-show="form.getFieldValue('storage_type') === STEnum.API.value">
          <a-form-item label="仓库第三方系统" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select
              v-if="typeList"
              v-decorator="['storage_key',{rules: [{ required: form.getFieldValue('storage_type') === STEnum.API.value }]}]"
              @change="handleChangeStorage"
              placeholder="请选择仓库第三方系统"
            >
              <a-select-option
                v-for="(item, index) in typeList"
                :key="index"
                :value="item.id"
              >{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            v-for="(item,idx) in storageParams"
            :key="idx"
            :label="item.field"
          >
            <a-input
              v-decorator="[
                `storage_params.${item.field}`,
                {rules:[{required:form.getFieldValue('storage_type') === STEnum.API.value,message:'请输入'+ item.field}]}
              ]"/>
            <p>{{ item.desc }}</p>

          </a-form-item>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import _ from 'lodash'
import * as Api from '@/api/supplier'
import { SelectImage } from '@/components'
import STEnum from '@/common/enum/store/supplier/StorageType'
export default {
  props: ['typeList'],
  components: {
    SelectImage
  },
  data () {
    return {
      STEnum,
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: { span: 7 },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录
      record: {},
      sid: null,
      storageParams: []
    }
  },
  methods: {

    /**
     * 显示对话框
     */
    edit (record) {
      // 显示窗口
      this.visible = true
      this.sid = record ? record.sid : null
      // 当前记录
      this.record = record || { storage_type: STEnum.API.value, storage_key: this.typeList[0].id }
      this.handleChangeStorage(this.record.storage_key)
      this.setFieldsValue()
    },

    /**
     * 设置默认值
     */
    setFieldsValue () {
      const { record, form: { setFieldsValue } } = this
      // 设置表单内容
      this.$nextTick(() => {
        const d = _.pick(record, ['name', 'full_name', 'phone', 'storage_type', 'storage_key'])
        let k
        for (k in record.storage_params) {
          d[`storage_params.${k}`] = record.storage_params[k]
        }
        setFieldsValue(d)
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        if (!errors) {
          this.onFormSubmit(values)
        }
      })
    },

    /**
     * 关闭对话框事件
     */
    handleCancel () {
      this.visible = false
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.confirmLoading = true
      if (this.sid) values.sid = this.sid
      Api[this.sid ? 'edit' : 'add'](values)
        .then((result) => {
          // 显示成功
          this.$message.success(result.message, 1.5)
          // 关闭对话框事件
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally((result) => {
          this.confirmLoading = false
        })
    },
    onForceUpdate (bool = false) {
      this.$forceUpdate()
      // bool为true时再执行一次 $forceUpdate, 特殊情况下需执行两次，原因如下：
      // 第一次执行 $forceUpdate时, 新元素绑定v-decorator无法获取到form.getFieldValue
      bool && setTimeout(() => {
        this.$forceUpdate()
      }, 10)
    },
    phoneCheck (rule, value, callbackFn) {
      if (!value) {
        callbackFn(true)
      } else if (value.length === 11 && !(/^(1[3456789]|9[28])\d{9}$/).test(value)) {
        callbackFn('请输入11位有效电话号码！')
      } else if (value.length !== 11) {
        callbackFn('请输入11位电话号码！')
      } else {
        callbackFn()
      }
    },
    handleChangeStorage (value) {
      this.typeList.forEach(row => {
        if (row.id === value) {
          this.storageParams = row.fields
        }
      })
    }

  }
}
</script>
